import requests
import time
import argparse

def get_repos_for_org(org_name: str, page: int, per_page: int, access_token: str, base_url: str) -> list:
    url = f"{base_url}/orgs/{org_name}/repos"
    params = {
        "access_token": access_token,
        "page": page,
        "per_page": per_page
    }
    response = requests.get(url, params=params)
    return response.json()

def fork_repo(org_name: str, repo_name: str, target_org: str, access_token: str, base_url: str):
    url = f"{base_url}/repos/{org_name}/{repo_name}/forks"
    params = {
        "access_token": access_token,
        "organization": target_org
    }
    response = requests.post(url, params=params)
    return response

def remove_repo(org_name: str, repo_name: str, access_token: str, base_url: str):
    url = f"{base_url}/repos/{org_name}/{repo_name}"
    params = {
        "access_token": access_token
    }
    response = requests.delete(url, params=params)
    return response

def batch_fork(origin_org: str, target_org: str, access_token: str, base_url: str):
    fork_list = []
    page = 0
    per_page = 50
    while True:
        repos = get_repos_for_org(origin_org, page, per_page, access_token, base_url)
        if not repos or len(repos) == 0:
            break
        for repo in repos:
            print(repo["full_name"])
            org_name, repo_name = repo["full_name"].split("/")
            if org_name == origin_org:
                fork_list.append(repo)
                print(f"add {repo['full_name']} to fork list")
            else:
                print(f"skip {repo['full_name']}")
        page += 1
    
    print(f"fork list length: {len(fork_list)}")
    input("press any key to continue")

    count = 0
    for repo in fork_list:
        org_name, repo_name = repo["full_name"].split("/")
        response = fork_repo(org_name, repo_name, target_org, access_token, base_url)
        if response.status_code == 201:
            print(f"fork {repo['full_name']} success")
        else:
            print(f"fork {repo['full_name']} failed")
            print(response.json())
        # wait for 1 second to avoid rate limit
        count += 1
        if count % 10 == 0:
            print(f"forked {count} repos")
        time.sleep(1)

def delete_not_match(access_token: str, base_url: str):
    delete_repos = []

    page = 1
    per_page = 100
    while True:
        repos = get_repos_for_org("oh-sdu", page, per_page, access_token, base_url)
        if not repos or len(repos) == 0:
            break
        for repo in repos:
            print(repo["full_name"])
            print(f"upstream repo: {repo['parent']['full_name']}")
            if not check_parent(repo['parent'], "openharmony"):
                delete_repos.append(repo)
                print(f"add {repo['full_name']} to delete list")
            else:
                print(f"skip {repo['full_name']}")
            print("=====================================")
        page += 1

    print(f"delete list length: {len(delete_repos)}")
    
    for repo in delete_repos:
        org_name, repo_name = repo["full_name"].split("/")
        response = remove_repo(org_name, repo_name, access_token, base_url)
        if response.status_code == 204:
            print(f"delete {repo['full_name']} success")
        else:
            print(f"delete {repo['full_name']} failed")
            print(response.json())
        # wait for 1 second to avoid rate limit
        time.sleep(1)

def check_parent(parent: dict, target_org: str)->bool:
    org_name, _ = parent["full_name"].split("/")
    return org_name == target_org

def get_commit_list(owner_name: str, repo_name: str, page: int, per_page: int, since: str, until: str, access_token: str, base_url: str):
    url = f"{base_url}/repos/{owner_name}/{repo_name}/commits"
    params = {
        "access_token": access_token,
        "page": page,
        "per_page": per_page,
        "since": since,
        "until": until,
    }
    response = requests.get(url, params=params)
    return response.json()

def weekly_commits(access_token: str, base_url: str):
    cur_time = time.time()
    
    # last week
    since = time.strftime("%Y-%m-%d", time.localtime(cur_time - 7 * 24 * 3600))
    until = time.strftime("%Y-%m-%d", time.localtime(cur_time))

def main():
    parser = argparse.ArgumentParser(description="Script to fork OpenHarmony repositories to another Gitee organization")
    parser.add_argument("--access_token", required=True, help="Access token for Gitee API")
    parser.add_argument("--origin_org", default="openharmony", help="Original organization name")
    parser.add_argument("--target_org", default="oh-sdu", help="Target organization name")
    parser.add_argument("--base_url", default="https://gitee.com/api/v5", help="Base URL for Gitee API")
    args = parser.parse_args()

    batch_fork(args.origin_org, args.target_org, args.access_token, args.base_url)

if __name__ == '__main__':
    main()
